package org.bee.tl.core.io;

import java.io.ByteArrayOutputStream;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.bee.tl.core.compile.CompiledClass;

public class CompileTemplateWriter extends ByteWriter {
	ByteWriter writer = null;
	CompiledClass cls = null;
	CompileTemplateWriter parent = null;

	public CompileTemplateWriter(ByteWriter byteWriter, CompiledClass cls) {
		super(byteWriter);
		this.cls = cls;

	}

	protected CompileTemplateWriter(ByteWriter byteWriter, CompiledClass cls,
			CompileTemplateWriter parent) {
		super(byteWriter);
		this.cls = cls;
		this.parent = parent;

	}

	public void write(String str) throws IOException {
		if (str != null) {
			super.write(str);
		}

	}

	public void write(Object o) throws IOException {
		if (o != null) {
			this.write(o.toString());
		}

	}

	public void write(int c) throws IOException {
		this.write(String.valueOf(c));
	}

	public void write(long c) throws IOException {
		this.write(String.valueOf(c));
	}

	public void write(double c) throws IOException {
		this.write(String.valueOf(c));
	}

	public void write(short c) throws IOException {
		this.write(String.valueOf(c));
	}

	public void write(float c) throws IOException {
		this.write(String.valueOf(c));
	}

	public void write(Object o, String funName, String pattern)
			throws IOException {
		this.write(cls.format(funName, o, pattern));
	}

	public void write(Object o, String funName) throws IOException {
		this.write(cls.format(funName, o, null));
	}

	public String toString() {
		return super.toString();
	}

	/**
	 * 用于标签实现，生成临时一个writer,使得标签的内容输出到这个临时的writer，标签实现程序可以根据写入wirte的内容做进一步处理
	 * 
	 * @see ort.bee.tl.core.Tag
	 * @return
	 */
	public CompileTemplateWriter getTempWriter() {
		if (isCharWriter) {
			return new CompileTemplateWriter(new ByteWriter(
					new CharArrayWriter(), true), cls, this);
		} else {
			try {

				return new CompileTemplateWriter(new ByteWriter(
						new ByteArrayOutputStream(), charset, true), cls, this);

			} catch (UnsupportedEncodingException e) {
				// could not happen,ignore
				throw new RuntimeException(e.getMessage());
			}
		}
	}

	public CompileTemplateWriter getParent() {
		return this.parent;
	}

	public void flush() throws IOException {
		super.flush();
	}

}
